using System;
using System.Collections.Generic;
using System.Text;
using LispInterpretor.HelperClasses;

namespace LispInterpretor.Parsers
{
    public class ProcedureParser : IParser
    {

        #region IParser Members

        public bool Is(string text, Environment environment)
        {
            try
            {
                string funcName = ParserHelper.ParseFuncName(text);

                return environment.Exists(funcName) && environment.Get(funcName) is Procedure;
            }
            catch (InvalidProgramException)
            {
                return false;
            }
        }

        public object Evaluate(string text, Environment environment)
        {
            object[] arguments = EvaluateArguments(text, environment);

            string procedureName = ParserHelper.ParseFuncName(text);

            Procedure proc = environment.Get(procedureName) as Procedure;

            return proc.Apply(arguments);
        }

        private object[] EvaluateArguments(string text, Environment environment)
        {
            IList<string> parsedItems = ParserHelper.ParseArguments(text);

            object[] items = new object[parsedItems.Count-1];

            for (int i = 1; i < parsedItems.Count; i++)
            {
                items[i - 1] = Evaluator.Eval(parsedItems[i], environment);
            }

            return items;
        }

        #endregion
    }
}
